package com.duan.laugh.activiti.controller;

import cn.hutool.core.io.IoUtil;
import com.duan.laugh.activiti.pojo.dto.ModelForm;
import com.duan.laugh.activiti.service.ModelService;
import com.duan.laugh.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.InputStream;
import java.util.Map;


/**
 * 工作流模型 controller
 *
 * @author duanjw
 */
@RestController
@RequestMapping("/model")
@AllArgsConstructor
public class ModelController {
    private final ModelService modelService;

    /**
     * 新增模型
     *
     * @param form
     * @return
     */
    @PostMapping(value = "/insert")
    public R<Boolean> insertForm(@RequestBody @Valid ModelForm form) {
        modelService.insert(form.getName(), form.getKey(), form.getDesc(), form.getCategory());
        return R.ok(Boolean.TRUE);
    }

    /**
     * 新增模型
     *
     * @param name
     * @param key
     * @param desc
     * @param category
     * @return
     */
    @PostMapping
    public R insert(@RequestParam String name, @RequestParam String key,
                    @RequestParam String desc, @RequestParam String category) {
        return R.ok(modelService.insert(name, key, desc, category));
    }

    /**
     * 分页查询模型
     *
     * @param params
     * @return
     */
    @GetMapping
    public R selectPage(@RequestParam Map<String, Object> params) {
        return R.ok(modelService.selectPage(params));
    }

    /**
     * 根据id删除模型
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R removeModelById(@PathVariable("id") String id) {
        return R.ok(modelService.removeModelById(id));

    }

    /**
     * 根据id部署模型到流程
     *
     * @param id
     * @return
     */
    @PostMapping("/deploy/{id}")
    public R deploy(@PathVariable("id") String id) {
        return R.ok(modelService.deploy(id));
    }

    /**
     * 根据id查看模型图
     *
     * @param id
     * @return
     */
    @GetMapping("/view/{id}")
    public ResponseEntity viewById(@PathVariable String id) {
        final InputStream inputStream = modelService.viewById(id);
        return new ResponseEntity(IoUtil.readBytes(inputStream), HttpStatus.CREATED);
    }
}
